<?php

namespace app\home\command;

use helper\RabbitMQ as Rabbit;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class RabbitMQ extends Command
{
    // php think worker server --city shanghai
    protected function configure()
    {
        // 指令配置
        $this->setName('rabbit')
            ->addArgument('name', Argument::OPTIONAL, "your task name")
            ->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
            ->setDescription('the rabbit command');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = $input->getArgument('name');
        $name = $name ? trim($name) : 'send';
        if ($name == 'send') {
            $this->send();
        } else {
            $this->receive();
        }

        if ($input->hasOption('city')) {
            $city = PHP_EOL . 'From ' . $input->getOption('city');
        } else {
            $city = '';
        }

        // 指令输出
        $output->writeln('async');
    }

    private function receive()
    {
        $mq = new Rabbit([], 'hello');

        echo " [*] Waiting for messages. To exit press CTRL+C\n";
        $callback = function ($msg) {
            echo ' [x] Received ', $msg->body, "\n";
        };
        $mq->receive($callback);
    }

    private function send()
    {
        $mq = new Rabbit([], 'hello');

        $mq->send('Hello World!', 'hello');
        echo " [x] Sent 'Hello World!'\n";
    }
}